package com.jhws.business.car.api;

import com.alibaba.fastjson.JSON;
import com.jhws.business.car.bo.*;
import com.jhws.business.car.service.*;
import com.jhws.common.base.bo.JsonRespData;
import com.jhws.common.pay.service.WXPayService;
import com.jhws.core.exception.BizException;
import com.jhws.core.mns.bo.MNSMessage;
import com.jhws.core.mns.service.IMNSService;
import com.jhws.util.LogHelper;
import com.jhws.util.QRCodeUtil;
import com.jhws.util.StringUtils;
import com.jhws.util.security.MD5Util;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/v2/car")
public class CarApiV2 extends CarApi {
    @Resource
    private CarInfoService carInfoService;
    @Resource
    private MNSMessageService mnsMessageService;
    @Resource
    private ParkingLotService parkingLotService;
    @Resource
    private CarEnteringRecordServic carEnteringRecordServic;
    @Resource
    private CarLaneService carLaneService;
    @Resource
    private IMNSService mnsService;
    @Resource
    private WXPayService wxPayService;
    @Resource
    private RedisTemplate stringTemplate;

    @RequestMapping("anon/queryCarInfo")
    @ResponseBody
    public JsonRespData queryCarInfo(String parkId, String plateNumber) {
        List<CarInfo> carInfos = carInfoService.queryCarInfoByWhere(" where park_id ='" + parkId + "' and plate_number = '" + plateNumber + "'");
        return new JsonRespData("", 1, carInfos != null && carInfos.size() > 0 ? carInfos.get(0) : null);
    }

    /**
     * 查询车道支付金额
     *
     * @param laneId
     * @return
     * @throws Exception
     */
    @RequestMapping("anon/queryCarLaneOrder")
    @ResponseBody
    public JsonRespData queryCarLaneOrder(Long laneId) throws Exception {
        CarLane carLane = carLaneService.queryCarLaneInfo(laneId);
        MNSMessage mnsMessage = mnsMessageService.queryCarLaneOrder(carLane.getParkId(), carLane.getLaneCode());
        if (mnsMessage != null) {
            CarLanePay carLanePay = JSON.parseObject(mnsMessage.getContent(), CarLanePay.class);
            if (carLanePay.getState() != null && carLanePay.getState() != 0) {
                return new JsonRespData("", -1, carLanePay.getErrorMsg());
            }
            return new JsonRespData("", 1, mnsMessage.getContent());
        }
        return new JsonRespData("", -1, "请求超时，没有获取到订单信息！");
    }

    /**
     * 查询车辆停车费
     *
     * @param parkId
     * @param plateNumber
     * @return
     * @throws Exception
     */
    @RequestMapping("anon/queryCarFeeQueue")
    @ResponseBody
    public JsonRespData queryCarFeeQueue(String parkId, String plateNumber) throws Exception {
        String queueName = "temp-" + MD5Util.md5(plateNumber);
        mnsMessageService.createQueue(queueName, 5, 60L);
        MNSMessage mnsMessage = mnsMessageService.queryCarFee(parkId, plateNumber, queueName);
        mnsMessageService.deleteQueue(queueName);
        if (mnsMessage != null) {
            CarLanePay carLanePay = JSON.parseObject(mnsMessage.getContent(), CarLanePay.class);
            if (carLanePay.getState() != null && carLanePay.getState() != 0) {
                return new JsonRespData("", -1, carLanePay.getErrorMsg());
            }
            return new JsonRespData("", 1, mnsMessage.getContent());
        }
        return new JsonRespData("", -1, "请求超时，没有获取停车信息！");
    }


    /**
     * 创建停车场
     *
     * @param parkingLot
     * @return
     */
    @RequestMapping("anon/createParkingLot")
    @ResponseBody
    public JsonRespData createParkingLot(@RequestBody ParkingLot parkingLot) {
        if (StringUtils.isEmpty(parkingLot.getParkId())) {
            return new JsonRespData("", -1, "停车场ID不能为空！");
        }
        if (StringUtils.isEmpty(parkingLot.getParkName())) {
            return new JsonRespData("", -1, "停车场名称不能为空！");
        }
        parkingLotService.saveParkingLot(parkingLot);
        return new JsonRespData("", 1, "Success");
    }

    /**
     * 创建车道
     *
     * @param carLane
     * @return
     */
    @RequestMapping("anon/createCarLane")
    @ResponseBody
    public JsonRespData createCarLane(@RequestBody CarLane carLane) {
        if (StringUtils.isEmpty(carLane.getParkId())) {
            return new JsonRespData("", -1, "停车场ID不能为空！");
        }
        if (StringUtils.isEmpty(carLane.getLaneName())) {
            return new JsonRespData("", -1, "车道名称不能为空！");
        }
        if (StringUtils.isEmpty(carLane.getLaneCode())) {
            return new JsonRespData("", -1, "车道编号不能为空！");
        }
        List<CarLane> carLanes = carLaneService.queryCarLanes("where park_id='" + carLane.getParkId() + "' and laneCode='" + carLane.getLaneCode() + "'");
        if (carLanes.size() > 0) {
            return new JsonRespData("", -1, "车道已经存在！");
        }
        carLaneService.saveCarLane(carLane);
        return new JsonRespData("", 1, "Success");
    }

    /**
     * 删除车道
     *
     * @param carLane
     * @return
     */
    @RequestMapping("anon/deleteCarLane")
    @ResponseBody
    public JsonRespData deleteCarLane(@RequestBody CarLane carLane) {
        if (StringUtils.isEmpty(carLane.getParkId())) {
            return new JsonRespData("", -1, "停车场ID不能为空！");
        }
        if (StringUtils.isEmpty(carLane.getLaneCode())) {
            return new JsonRespData("", -1, "车道编号不能为空！");
        }
        carLaneService.deleteCarLane("where park_id='" + carLane.getParkId() + "' and lane_code='" + carLane.getLaneCode() + "'");
        return new JsonRespData("", 1, "Success");
    }

    /**
     * 车辆入场
     *
     * @param carEnteringRecord
     * @return
     */
    @RequestMapping("anon/entryRecord")
    @ResponseBody
    public JsonRespData entryRecord(@RequestBody CarEnteringRecord carEnteringRecord) {
        if (StringUtils.isEmpty(carEnteringRecord.getParkId())) {
            return new JsonRespData("", -1, "停车场ID不能为空！");
        }
        if (StringUtils.isEmpty(carEnteringRecord.getPlateNumber())) {
            return new JsonRespData("", -1, "车牌号码不能为空！");
        }
        if (carEnteringRecord.getTime() == null) {
            return new JsonRespData("", -1, "进场时间不能为空！");
        }
        carEnteringRecord.setBussinessType(CarConstant.CAR_BUSSINESS_IN_TYPE);
        carEnteringRecordServic.saveCarEntering(carEnteringRecord);
        HashOperations hashOperations = stringTemplate.opsForHash();
        hashOperations.put(CarConstant.REDIS_HEAD_PARKING_LOT + carEnteringRecord.getParkId(), carEnteringRecord.getPlateNumber(), "");
        return new JsonRespData("", 1, "Success");
    }

    /**
     * 车辆出场
     *
     * @param carEnteringRecord
     * @return
     */
    @RequestMapping("anon/exitRecord")
    @ResponseBody
    public JsonRespData exitRecord(@RequestBody CarEnteringRecord carEnteringRecord) {
        if (StringUtils.isEmpty(carEnteringRecord.getParkId())) {
            return new JsonRespData("", -1, "停车场ID不能为空！");
        }
        if (StringUtils.isEmpty(carEnteringRecord.getPlateNumber())) {
            return new JsonRespData("", -1, "车牌号码不能为空！");
        }
        if (carEnteringRecord.getTime() == null) {
            return new JsonRespData("", -1, "出场时间不能为空！");
        }
        if (StringUtils.isEmpty(carEnteringRecord.getPeriod())) {
            return new JsonRespData("", -1, "停车时长不能为空！");
        }
        LogHelper.d("CarEnteringRecord" + carEnteringRecord.toString());
        carEnteringRecord.setBussinessType(CarConstant.CAR_BUSSINESS_OUT_TYPE);
        carEnteringRecordServic.saveCarEntering(carEnteringRecord);
        HashOperations hashOperations = stringTemplate.opsForHash();
        hashOperations.delete(CarConstant.REDIS_HEAD_PARKING_LOT + carEnteringRecord.getParkId(), carEnteringRecord.getPlateNumber());
        return new JsonRespData("", 1, "Success");
    }

    /**
     * 车道支付
     *
     * @param carLanePay
     * @return
     * @throws Exception
     */
    @SuppressWarnings("ResultOfMethodCallIgnored")
    @RequestMapping("anon/carLanePay")
    @ResponseBody
    public JsonRespData carLanePay(@RequestBody CarLanePay carLanePay) throws Exception {
        LogHelper.d("---------------->   carLanePay  " + carLanePay.toString());
        if (StringUtils.isEmpty(carLanePay.getParkId())) {
            return new JsonRespData("", -1, "停车场ID不能为空！");
        }
        if (StringUtils.isEmpty(carLanePay.getLaneCode())) {
            return new JsonRespData("", -1, "车道编码不能为空！");
        }
        if (StringUtils.isEmpty(carLanePay.getPlateNumber())) {
            return new JsonRespData("", -1, "车牌号码不能为空！");
        }
        try {
            Double.parseDouble(carLanePay.getPayments());
        } catch (NumberFormatException e) {
            return new JsonRespData("", -1, "付款金额错误！");
        }
        if (StringUtils.isEmpty(carLanePay.getPeriod())) {
            return new JsonRespData("", -1, "停车时长不能为空！");
        }
        try {
            mnsService.producer(carLanePay.getParkId() + "-" + carLanePay.getLaneCode(), JSON.toJSONString(carLanePay));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new JsonRespData("", 1, "Success");
    }

    /**
     * 查询停车费用返回接口
     *
     * @param carLanePay
     * @return
     * @throws Exception
     */
    @SuppressWarnings("ResultOfMethodCallIgnored")
    @RequestMapping("anon/queryCarFee")
    @ResponseBody
    public JsonRespData queryCarFee(@RequestBody CarLanePay carLanePay) throws Exception {
        if (carLanePay.getState() == null || carLanePay.getState() == 0) {
            if (StringUtils.isEmpty(carLanePay.getParkId())) {
                return new JsonRespData("", -1, "停车场ID不能为空！");
            }
            if (StringUtils.isEmpty(carLanePay.getPlateNumber())) {
                return new JsonRespData("", -1, "车牌号码不能为空！");
            }
            try {
                Double.parseDouble(carLanePay.getPayments());
            } catch (NumberFormatException e) {
                return new JsonRespData("", -1, "停车金额错误！");
            }
            if (StringUtils.isEmpty(carLanePay.getPeriod())) {
                return new JsonRespData("", -1, "停车时长不能为空！");
            }
        }
        LogHelper.d("---------------->   queryCarFee  " + carLanePay.toString());
        try {
            mnsService.producer("temp-" + MD5Util.md5(carLanePay.getPlateNumber()), JSON.toJSONString(carLanePay));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new JsonRespData("", 1, "Success");
    }

    /**
     * 创建车道支付二维码
     *
     * @param response
     * @param request
     * @param parkId
     * @param laneCode
     * @throws IOException
     */
    @RequestMapping("anon/qrcode.jpg")
    public void createQRCode(HttpServletResponse response, HttpServletRequest request, String parkId, String laneCode) throws Exception {
        if (StringUtils.isEmpty(parkId) || StringUtils.isEmpty(laneCode)) {
            throw new BizException("-1", "", "参数错误！");
        }
        ParkingLot parkingLot = parkingLotService.queryParkingLotInfo(parkId);
        if (parkingLot == null || parkingLot.getPayCustomerId() == 0) {
            throw new BizException("-1", "", "停车场参数错误！");
        }
        List<CarLane> carLanes = carLaneService.queryCarLanes("where park_id='" + parkId + "' and laneCode='" + laneCode + "'");
        if (carLanes.size() > 0) {
            String domainName = request.getScheme() + "://" + request.getServerName();
            //禁止缓存
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setHeader("Content-Disposition", "attachment;fileName=qrcode.jpg");
            String webUrl = "/api/v2/car/anon/laneQrcode?laneId=" + carLanes.get(0).getId() + "&" + "appId=" + wxPayService.getAppId(parkingLot.getPayCustomerId());
            String url = domainName + webUrl;
            ImageIO.write(QRCodeUtil.createImage(url, null, true), "JPEG", response.getOutputStream());
            response.getOutputStream().flush();
        } else {
            throw new BizException("-1", "", "车道不存在！");
        }
    }

    /**
     * 获取车道支付二维码内容
     *
     * @param request
     * @param parkId
     * @param laneCode
     * @return
     * @throws IOException
     */
    @RequestMapping("anon/qrcodeInfo")
    @ResponseBody
    public JsonRespData qrcodeInfo(HttpServletRequest request, String parkId, String laneCode) throws Exception {
        if (StringUtils.isEmpty(parkId) || StringUtils.isEmpty(laneCode)) {
            return new JsonRespData("", -1, "参数错误！");
        }
        ParkingLot parkingLot = parkingLotService.queryParkingLotInfo(parkId);
        if (parkingLot == null || parkingLot.getPayCustomerId() == 0) {
            return new JsonRespData("", -1, "停车场参数错误！");
        }
        List<CarLane> carLanes = carLaneService.queryCarLanes("where park_id='" + parkId + "' and laneCode='" + laneCode + "'");
        if (carLanes.size() > 0) {
            String domainName = request.getScheme() + "://" + request.getServerName();
            String webUrl = "/api/v2/car/anon/laneQrcode?laneId=" + carLanes.get(0).getId() + "&" + "appId=" + wxPayService.getAppId(parkingLot.getPayCustomerId());
            String url = domainName + webUrl;
            return new JsonRespData("", 1, url);
        } else {
            return new JsonRespData("", -1, "车道不存在！");
        }
    }

    /**
     * 判断是微信还是支付宝，返回不同的数据， 车道支付
     *
     * @param request
     * @param laneId
     * @param appId
     * @return
     */
    @RequestMapping("anon/laneQrcode")
    public String laneQrcode(HttpServletRequest request, String laneId, String appId) {
        String baseUrl = "/pages/mobile/car/scan/lane/index.html?laneId=" + laneId;
        return "redirect:" + wxPayService.getCompatibleUrlForWxAndAlipay(request, baseUrl, appId);
    }

    /**
     * 判断是微信还是支付宝，返回不同的数据,预支付
     *
     * @param request
     * @param parkId
     * @param appId
     * @return
     */
    @RequestMapping("anon/orderedQrcode")
    public String orderedQrcode(HttpServletRequest request, String parkId, String appId) {
        String baseUrl = "/pages/mobile/car/scan/pre/index.html?parkId=" + parkId;
        return "redirect:" + wxPayService.getCompatibleUrlForWxAndAlipay(request, baseUrl, appId);
    }

    /**
     * 判断是微信还是支付宝，返回不同的数据,月卡web扫码支付
     *
     * @param request
     * @param orderId
     * @param appId
     * @return
     */
    @RequestMapping("anon/monthQrcode")
    public String monthQrcode(HttpServletRequest request, String orderId, String appId) {
        String baseUrl = "/pages/mobile/car/scan/month/monthPay.html?orderId=" + orderId;
        return "redirect:" + wxPayService.getCompatibleUrlForWxAndAlipay(request, baseUrl, appId);
    }
}
